export function AMapGeocoder () {
  // if (window.AMap) return Promise.resolve()
  return new Promise(function (resolve, reject) {
    var script = document.createElement('script')
    script.type = 'text/javascript'
    script.src =
      'https://webapi.amap.com/maps?v=2.0&key=' +
      'dacb85f968e40b008f30eaadaa9e6ae1' +
      '&plugin=AMap.Geocoder'
    console.log(script)
    script.onerror = e => reject(e)
    script.onload = () => resolve()
    document.head.appendChild(script)
  })
}

export function AMapCircleEditor () {
  // if (window.AMap.CircleEditor) return Promise.resolve()
  return new Promise(function (resolve, reject) {
    var script = document.createElement('script')
    script.type = 'text/javascript'
    script.src =
      'https://webapi.amap.com/maps?v=2.0&key=' +
      'dacb85f968e40b008f30eaadaa9e6ae1' +
      '&plugin=AMap.CircleEditor'
    console.log(script)
    script.onerror = e => reject(e)
    script.onload = () => resolve()
    document.head.appendChild(script)
  })
}

export function checkGdLocation () {
  console.log(2)
  return new Promise((resolve, reject) => {
    AMapGeocoder().then(() => {
      // eslint-disable-next-line no-undef
      AMap.plugin(['AMap.Geolocation'], function () {
        // eslint-disable-next-line no-undef
        var geolocation = new AMap.Geolocation()
        geolocation.getCurrentPosition(function (status, result) {
          if (status === 'complete') {
            onComplete(result)
          } else {
            onError(result)
          }
        })
        function onComplete (data) {
          console.log('定位成功', data)
          resolve(true)
        }
        function onError (data) {
          console.error('定位失败', data)
          reject(new Error(data))
        }
      })
    })
  })
}
